﻿/*
 * 由SharpDevelop创建。
 * 用户： Admin
 * 日期: 2025/5/4
 * 时间: 17:51
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Text;

namespace SayCh
{
	/// <summary>
	/// 后台指令 saych [msg] - 将msg使用unicode编码后发送给js指定接口下
	/// </summary>
	public static class SayCh
	{
		public static BDSCSBox.DataAdapter handle = null;
		
		public const string ADDONJS_KEY_SAYCH = "sysmsg:msg";
		
		public static string EscapeUnicode(string str) // 将字符串编码为unicode转义序列 (\\uxxxx)
		{
		StringBuilder tmp = new StringBuilder();
		for (int i = 0; i < str.Length; i++)
		{
		ushort uxc = (ushort)str[i];
		tmp.Append(@"\u" + uxc.ToString("x4"));
		}
		return tmp.ToString();
		}
		
		static bool onSend(string msg) {
			if (msg.IndexOf("saych") > -1) {
				// 发送一条中文消息给AddonJs，绑定关键字 sysmsg:msg
				int i = msg.IndexOf("saych");
				var submsg = msg.Substring(i + 5);
				if (!string.IsNullOrEmpty(submsg)) {
					submsg = submsg.Trim();
				}
				var tojmsg = "scriptevent " + ADDONJS_KEY_SAYCH + " " + EscapeUnicode(submsg);
				handle.sendMsg(tojmsg);
				return false;
			}
			return true;
		}
		
		public static BDSCSBox.TYPES.F_FUNC sender = onSend;
		
	}
}

/*
 * JS解码代码如下：
 * 
var GB2312UnicodeConverter = {
ToUnicode: function(str) {
return escape(str).toLocaleLowerCase().replace(/%u/gi, '\\u');
},
ToGB2312: function(str) {
return unescape(str.replace(/\\u/gi, '%u'));
}
};
*/

namespace BDSCSBox {
	public class CSL {
		public bool onStart(BDSCSBox.DataAdapter handle) {	// dll入口，注册所有函数
			SayCh.SayCh.handle = handle;
			handle.addDataSender(SayCh.SayCh.sender);
			Console.WriteLine("[SayCh] unicode编码指令saych已加载。");
			return true;
		}
	}
}